<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\Area;
use app\common\tool\Result;
use think\facade\View;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\response\Json;

class Address extends Base
{

    public function index()
    {
        View::assign('list', AddressModel::getList(['uid' => $this->user->id], false, 'create_time', ['p', 'c', 'd', 't']));
        $tpl = $this->request->param('type') ? 'choice' : 'index';
        return View::fetch($tpl);
    }


    public function add($id = '')
    {
        if ($id) {
            View::assign('info', AddressModel::where('id', $id)->find());
        }
        return View::fetch();
    }


    public function save(): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Address');
            return json(AddressModel::add($param, $this->user));
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
    }

    public function delete(): Json
    {
        return json(AddressModel::edit($this->request->post('id'), $this->user));
    }

    public function choice(): Json
    {
        return json(AddressModel::choice($this->request->post('id'), $this->user));
    }


    public function getArea($pid, $deep = 0)
    {
        return Result::success('success', Area::getArea($pid ?: 0, $deep));
    }


    public function defaultAddress()
    {
        AddressModel::update(['default' => 0], ['uid' => $this->user->id]);
        AddressModel::update(['default' => 1], ['id' => $this->request->post('id')]);
        return json(['code' => 1, 'msg' => '已设为默认地址']);
    }

}

